#!/usr/bin/python

#-----LIBRARY IMPORT-- 
import dircache
import re
import os.path
import os
import shutil
#--------------------


#-----PLATFORM--------
## this is only a debug option because i'm developing this script on my iMac and on my eeePC

import platform 

if platform.system() == 'Darwin':
	ROOT_PATH = "/Users/marco/Dropbox/torrent/"
elif platform.system() == 'Linux':
	ROOT_PATH = "/home/dac/"
#--------------------
	
	
#-----CONFIG---------
## i've to port this in an external config file

#DROPBOX_PATH = "Desktop/"
#DOWNLOAD_PATH = ROOT_PATH + DROPBOX_PATH + "download/"
DOWNLOAD_PATH = ROOT_PATH + "complete/"
COMPLETE_PATH = "/Volumes/VIDEO/Telefilm/"
#--------------------


#-----CLASS----------
class episode:
	def __init__(self, serie, season, episode, file_name):
		self.serie = re.sub('\.', ' ', serie[:-1]) 	#the last char is a .
		self.season = re.sub('[s,S]', '', season)
		self.episode = re.sub('[e,E]', '', episode)	#actually this isn't used...
		self.file_name = file_name
		
##Check path is ok, here is where i've to add the check for file
	def checkPath(self, path):
		self.path = os.path.abspath(path)	#normalize path
		if not os.path.exists(self.path):	#check if path exist
			try:
				os.makedirs(self.path)
			except OSError as error:
				print 'There is an error: ', error
				return 0
			else:
				if os.path.exists(self.path):
					return 1
				else:
					return 0
		else:	#here if path exist
			return 1	

##Copy the file
	def doCopy(self, ori_path, dest_path):
		if self.checkPath(dest_path):
			shutil.move(ori_path+self.file_name, dest_path)	
			print "Copied file: ", self.file_name
			
			
#-----GETTERS----------
	def getSeason(self):
		return self.season
	
	def getSerie(self):
		return self.serie

	def getEpisode(self):
		return self.episode
		
#--------------------
##END CLASS


#-----MAIN-----------
#this is an ls on donwload folder
dir = dircache.listdir(DOWNLOAD_PATH)

i=0

for file in dir:
	if file[-4:]=='.avi':	#i'm interested only in .avi file for now
		#Optimizing the REGEX is a taks TODO
		data = re.match('([A-Z,a-z,\.]+(?=[s,S][0-9]{2}))([s,S][0-9]{2})([e,E][0-9]{2})', file)
		e = episode(data.group(1), data.group(2), data.group(3), file)
		destination_path = COMPLETE_PATH + e.getSerie() + '/' + 'Season ' + e.getSeason() + '/'
		
		#implementig usefull error handling
		e.doCopy(DOWNLOAD_PATH, destination_path)
		print "Finished!"

#--------------------